type DynamometerMeasurement = {
  value: string;
  unit: string;
  rawData: string;
  timestamp: string;
  isComplete?: boolean; // 添加检测完成标志
};

class DynamometerParser {
  static readonly SERVICE_UUID: string = '0000ffe0-0000-1000-8000-00805f9b34fb';
  static readonly DATA_CHARACTERISTIC: string = '0000ffe4-0000-1000-8000-00805f9b34fb';
  static readonly COMMAND_SERVICE: string = '0000ffe5-0000-1000-8000-00805f9b34fb';
  static readonly COMMAND_CHARACTERISTIC: string = '0000ffe9-0000-1000-8000-00805f9b34fb';

  // 初始化命令序列
  static readonly INIT_COMMANDS: string[] = [
    "a50a01030405060708d1",
    "a5050700b1",
    "a5050301ae",
    "a50b0607e90605170136ff",
    "a505054bfa"
  ];

  // 操作命令
  static readonly START_COMMAND: string = "a5051100bb";
  static readonly STOP_COMMAND: string = "a5051105c0";

  static parseData(hexString: string): DynamometerMeasurement {
    if (!hexString || hexString.length < 18) { // 至少9字节 = 18个十六进制字符
      console.log('数据帧长度错误:', hexString.length)
    }

    // 检查帧头
    const header = hexString.substr(0, 2);
    if (header !== '5a') {
      console.log('帧头错误:', header)
    }

    // 提取握力值 (第5-6字节，大端序)
    const rawValue = hexString.substr(8, 4);
    const value = parseInt(rawValue, 16) / 10;

    // 检查检测完成标志 (第4个字节，即索引6-7的字符)
    // 根据用户提供的示例，当5a09110100f60064cf中的"01"表示检测结束
    // 这个"01"位于第4字节
    const statusByte = hexString.substr(6, 2); // 第4字节 (索引6-7)
    const statusValue = parseInt(statusByte, 16); 
    const isComplete = statusValue === 0x01; // 如果第4字节为0x01，表示检测完成
    console.log(`检测完成标志分析: 状态字节=${statusByte}, 状态值=${statusValue}, 是否完成=${isComplete}`);

    // 校验和验证
    const checksum = parseInt(hexString.substr(16, 2), 16);
    let calculatedChecksum = 0;
    for (let i = 0; i < 8; i++) {
      calculatedChecksum += parseInt(hexString.substr(i*2, 2), 16);
    }
    calculatedChecksum = calculatedChecksum & 0xFF;

    if (calculatedChecksum !== checksum) {
      throw new Error('Checksum mismatch');
    }

    return {
      value: value.toFixed(1),
      unit: 'kg',
      rawData: hexString,
      timestamp: new Date().toISOString(),
      isComplete: isComplete
    };
  }

  static getInitCommands(): string[] {
    return this.INIT_COMMANDS;
  }

  static getStartCommand(): string {
    return this.START_COMMAND;
  }

  static getStopCommand(): string {
    return this.STOP_COMMAND;
  }
}

export default DynamometerParser;
export type { DynamometerMeasurement };

